<template>
  <div class="module-box">
    <SectionTitle title="订单信息" style="margin: 16px 0;">
      <el-tooltip :open-delay="300" placement="top" effect="dark">
        <div slot="content" style="max-width: 180px; line-height: 1.5">{{ relatedOrderTip }}</div>
        <tipIcon is-diy style="margin-left: 8px"/>
      </el-tooltip>
      <div class="total-amount-price">
        <img :src="incomeAmountIcon" alt="">
        总含税金额：<span class="price">{{ totalAmount }}</span>
      </div>
      <div class="options-btn-group">
        <PlainCreateBtn @click="onOrderAdd">添加</PlainCreateBtn>
        <el-button size="small" class="option-btn" @click="onOrderRelevance">关联订单</el-button>
        <el-button :disabled="deleteDisable" size="small" type="danger" plain class="option-btn" @click="handleRowsDel">删除</el-button>
      </div>
    </SectionTitle>
    <dynamicEditTable
      ref="dynamicEditTableRef"
      v-model="orders"
      :list-setting="listSetting()"
      :is-edit="true"
      :show-serial="false"
      :show-add-btn="false"
      :default-params="defaultOrderItem"
      :order-private-id="orderPrivateId"
      is-fill
      show-selection
      @onSelectChange="onSelectChange"
      @orderPrivateIdChange="orderPrivateIdChange"
    />
    <related-orders
      ref="relatedOrders"
      :visible.sync="showRelatedOrders"
      :is-exclude-order-mode="false"
      :except-review-status="false"
      @confirmRelatedOrder="confirmRelatedOrder"
      @onBack="relatedDrawerHide"
    />
  </div>
</template>

<script>
import SectionTitle from '@/components/Title';
import dynamicEditTable from '@/components/Common/dynamicEditTable';
import relatedOrders from '@/components/legal/relatedOrders';
import OperationRelatedOrders from '@/views/legal/create/mixins/operationRelatedOrders';
import { issueInvoiceOrderSetting } from '@/views/legal/module/orderSetting';
import { platformList } from '@/api/select';
import incomeAmountIcon from '@/assets/chargeOffDetail/incomeAmount.png';

export default {
  name: 'OrderInfo',
  components: {
    SectionTitle,
    relatedOrders,
    dynamicEditTable
  },
  mixins: [OperationRelatedOrders],
  data() {
    return {
      incomeAmountIcon,
      issueInvoiceOrderSetting,
      defaultOrderItem: {
        customizeState: true
      },
      orders: [{
        customizeState: true,
        orderPrivateId: 1
      }],
      orderPrivateId: 1,
      deleteDisable: true,
      curSelectedRows: [],
      defaultList: {
        'createInfo.proposer': []
      },
      showRelatedOrders: false,
      totalAmount: 0.00
    };
  },
  computed: {
    relatedOrderTip() {
      return '批量关联的订单仅获取填充当时关联的订单信息，不随订单信息更新而改变该列表的信息';
    }
  },
  watch: {
    orders: {
      handler(list) {
        const result = list.reduce((total, curr) => {
          const price = Number(curr.contractPrice) ? Number(curr.contractPrice) : 0;
          return price + total;
        }, 0);
        this.totalAmount = Number(result).toFixed(2);
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.queryPlatformList();
  },
  methods: {
    // 获取下单平台的列表
    async queryPlatformList() {
      try {
        const result = await platformList();
        if (this.issueInvoiceOrderSetting) {
          this.issueInvoiceOrderSetting.forEach(i => {
            if (i.label === '下单平台') {
              this.$set(i, 'options', result.data);
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },
    onOrderAdd() {
      this.$refs['dynamicEditTableRef'].addValue();
    },
    // 提供给父组件来验证完整性
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs['dynamicEditTableRef'].validate().then(() => {
          resolve();
        }).catch(() => {
          reject();
        });
      });
    },
    resetFormValidate() {
      this.$refs['dynamicEditTableRef'].errorIds = [];
    },
    onOrderRelevance() {
      this.formatOrderToTable(this.orders);
      this.showRelatedOrders = true;
      this.$refs['relatedOrders'].init();
    },
    handleRowsDel() {
      this.$confirm('确认删除已选中的订单信息吗？', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        let curRow;
        // eslint-disable-next-line no-cond-assign
        while (curRow = this.curSelectedRows.pop()) {
          for (let index = this.orders.length - 1; index >= 0; index--) {
            if (this.orders[index].orderPrivateId === curRow.orderPrivateId) {
              this.orders.splice(index, 1);
            }
          }
        }
      });
    },
    listSetting() {
      const setting = this.issueInvoiceOrderSetting;
      const isProject = this.orders.some(i => {
        return i.orderType === 2;
      });
      setting.forEach(item => {
        item.isRequired = true;
        if (item.keyword === 'orderNum') { // 3.2.1订单编号改成非必填
          item.isRequired = false;
        }
        // 只要有项目订单，就不用判断执行账号、下单平台 必填项
        if (isProject && (item.keyword === 'exeAccount' || item.keyword === 'orderPlatform')) {
          item.isRequired = false;
        }
      });
      return setting;
    },
    onSelectChange(list) {
      this.curSelectedRows = list;
      this.deleteDisable = !list.length || !(list.length < this.orders.length);
    },
    orderPrivateIdChange(num) {
      if (!num) return;
      this.orderPrivateId = num;
    },
    confirmRelatedOrder(data) {
      this.setOrders(data);
      this.relatedDrawerHide();
    },
    relatedDrawerHide() {
      this.showRelatedOrders = false;
    },
    getOrderData() {
      const params = {};
      params.orderTotalAmount = this.totalAmount;
      params.list = this.orders;
      return params;
    },
    setTableData(list) {
      list.forEach(item => {
        item.disable = !item.customizeState;
        item.orderPrivateId = this.orderPrivateId++;
      });
      this.orders = list;
    }
  }
};
</script>

<style scoped lang="scss">
.module-box {
  // margin-bottom: 40px;
  padding-bottom: 16px;
  .total-amount-price {
    display: flex;
    align-items: center;
    background-color: #f8f8f8;
    color: #999;
    font-size: 12px;
    font-weight: normal;
    margin-left: 10px;
    padding: 4px 6px;
    border-radius: 4px;
    > img {
      width: 14px;
      margin-right: 5px;
    }
    .price {
      font-size: 14px;
      color: #406eff;
      font-weight: bold;
    }
  }
  .options-btn-group {
    position: absolute;
    right: 0;
    .option-btn {
      padding-left: 12px;
      padding-right: 12px;
    }
  }
}
::v-deep .dynamic-container {
  .el-table__row {
    .cell {
      .el-input__inner {
        height: 48px !important;
      }
    }
  }
}
</style>
